const router = require("koa-router")();
const { query } = require("./../config/dbPool");
const {
  DEPTLIST_SQL,
  DEPTINFO_SQL,
  DEPTADD_SQL,
  DEPTUPDATE_SQL,
  DEPTDELETE_SQL,
} = require("./../config/dbSQL");

router.prefix("/dept");

/**
 * 查询系别列表
 * @url /dept/list
 */
router.get("/list", async (ctx) => {
  const res = JSON.parse(JSON.stringify(await query(DEPTLIST_SQL)));
  if (res.result) {
    ctx.body = {
      status: 200,
      result: true,
      data: res.data,
      message: "获取成功",
    };
  }
});

/**
 * 获取系别详情
 * @url /dept/:dept_id/info
 */
router.get("/:dept_id/info", async (ctx) => {
  const dept_id = ctx.params.dept_id;
  const res = JSON.parse(JSON.stringify(await query(DEPTINFO_SQL, [dept_id])));
  if (res.result) {
    ctx.body = {
      status: 200,
      result: true,
      data: {
        ...res.data[0],
      },
      message: "获取成功",
    };
  } else {
    ctx.body = {
      status: 200,
      result: false,
      message: "获取失败",
    };
  }
});

/**
 * 添加系别
 * @url /dept/add
 */
router.post("/add", async (ctx) => {
  const request = ctx.request.body;
  const { dept_id, dept_name } = request;
  const queryData = {
    dept_id,
    dept_name,
  };
  if (dept_id) {
    const data = JSON.parse(
      JSON.stringify(await query(DEPTINFO_SQL, [dept_id]))
    );
    if (data.result && data.data.length > 0) {
      ctx.body = {
        status: 200,
        result: false,
        message: "系别已存在",
      };
      return;
    }
    const res = await query(DEPTADD_SQL, queryData);
    if (res.result) {
      ctx.body = {
        status: 200,
        result: true,
        message: "添加成功",
      };
    } else {
      ctx.body = {
        status: 200,
        result: false,
        message: "添加失败",
      };
    }
  }
});

/**
 * 修改系别
 * @url /dept/:dept_id/info
 */
router.put(`/:dept_id/info`, async (ctx) => {
  const request = ctx.request.body;
  const dept_id = ctx.params.dept_id;
  const { dept_name } = request;
  const queryData = [dept_name, dept_id];
  const res = await query(DEPTUPDATE_SQL, queryData);
  if (res.result) {
    ctx.body = {
      status: 200,
      result: true,
      message: "修改成功",
    };
  } else {
    ctx.body = {
      status: 200,
      result: false,
      message: "修改失败",
    };
  }
});

/**
 * 删除系别
 * @url /dept/:dept_id/info
 */
router.delete(`/:dept_id/info`, async (ctx) => {
  const dept_id = ctx.params.dept_id;
  if (dept_id) {
    const res = await query(DEPTDELETE_SQL, [dept_id]);
    if (res.result) {
      ctx.body = {
        status: 200,
        result: true,
        message: "删除成功",
      };
    } else {
      ctx.body = {
        status: 200,
        result: false,
        message: "删除失败",
      };
    }
  }
});

module.exports = router;
